package com.gesonet.oauth2.util.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/**
 * @Description: Object对象Json转换
 * @author QXX
 * @date 2014年10月19日 下午8:10:20
 */
public class JsonUtils {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    public static Object TO_OBJ(String source, Class<?> clazz){
		return JSON.parseObject(source, clazz);
	}
    
    public static String map2JsonString(Map<String, Object> map) {
		try {
			return JacksonJsonMapper.getInstance().writeValueAsString(map);
		} catch (IOException e) {
			logger.error("转换JSON失败！", e);
		}
		return "";
	}
    
    /**
     * @author QXX
     * @date 2014年10月23日 下午5:56:25
     * @Description: Json中data数据转为对象 
     * @param json 
     * @param clazz
     * @return
     * @throws
     */
    public static <T> T json2Bean(JsonNode node, Class<T> clazz) {
        try {
            return JacksonJsonMapper.getInstance().readValue(node, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    public static <T> List<T> json2List(String json, Class<T> clazz) {
		List<T> list = new ArrayList<T>();
		if (StringUtils.isBlank(json)) {
			return list;
		}
		try {
			JsonNode nodes = JacksonJsonMapper.getInstance().readTree(json);
			for (JsonNode jsonNode : nodes) {
				T t = json2Bean(jsonNode, clazz);
				list.add(t);
			}
		} catch (Exception e) {
			logger.error("json数据不合法：" + json);
			e.printStackTrace();
		}
		return list;
	}
    
	public static String toJSONString(Object obj) {
		try {
			return JacksonJsonMapper.getInstance().writeValueAsString(obj);
		} catch (Exception e) {
			logger.error("转换json失败", e);
			return "";
		}
	}
	
	public static Map<String,Object> json2Map(String json){
		Map<String,Object> map = new HashMap<>();
		try {
			JsonNode nodes = JacksonJsonMapper.getInstance().readTree(json);
			for (JsonNode jsonNode : nodes) {
				if(jsonNode.isArray()){
					Iterator<String> names = jsonNode.getFieldNames();
					while (names.hasNext()) {
						String name = (String) names.next();
						List<String> list = jsonNode.findValuesAsText(name);
						map.put(name, list);
					}
				}else{
					
				}
			}
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return map;
	}

}
